package org.xshaokuang.loginandemail.email;

import cn.nukkit.Player;
import cn.nukkit.command.Command;
import cn.nukkit.command.CommandSender;
import cn.nukkit.item.Item;
import cn.nukkit.utils.Config;
import org.xshaokuang.loginandemail.MainPlugin;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class EmailSendCommand extends Command {
    private final EmailDataManager emailManager;

    private final Config config;

    public EmailSendCommand(EmailDataManager emailManager, Config config)  {
        super(
                "xemailsend",
                "发送邮件给玩家",
                "/xemailsend <玩家> <保留天数> <文本> <是否发送物品true/false>"
        );
        this.emailManager = emailManager;
        this.config = config;
        this.setPermission("email.command.send"); // 权限节点（可选）
    }

    @Override
    public boolean execute(CommandSender sender, String label, String[] args) {
        // 验证执行者为玩家
        if (!(sender instanceof Player)) {
            sender.sendMessage("§c只有玩家可以使用此命令");
            return false;
        }
        Player player = (Player) sender;

        // 参数校验
        if (args.length != 4) {
            player.sendMessage("§c用法: /xemailsend <玩家> <保留天数> <文本> <是否发送物品>");
            return false;
        }

        // 解析目标玩家
        String targetPlayer = args[0];

        // 解析保留天数
        int keepDays;
        try {
            keepDays = Integer.parseInt(args[1]);
            if (keepDays <= 0) {
                player.sendMessage("§c保留天数必须大于0");
                return false;
            }
        } catch (NumberFormatException e) {
            player.sendMessage("§c无效的保留天数格式");
            return false;
        }

        // 解析邮件内容
        String text = args[2].replace("&", "§"); // 支持颜色代码

        // 解析是否发送物品
        boolean sendItem;
        if (args[3].equalsIgnoreCase("true")) {
            sendItem = true;
        } else if (args[3].equalsIgnoreCase("false")) {
            sendItem = false;
        } else {
            player.sendMessage("§c是否发送物品参数必须为true/false");
            return false;
        }

        // 处理物品附件
        List<Item> attachments = new ArrayList<>();
        if (sendItem) {
            Item handItem = player.getInventory().getItemInHand();

            // 检查手持物品有效性
            if (handItem.getId() == Item.AIR) {
                player.sendMessage("§c你当前没有手持任何物品");
                return false;
            }

            // 克隆物品防止修改原始对象
            Item attachment = handItem.clone();
            attachments.add(attachment);

            // 非创造模式扣除物品
            if (!player.isCreative()) {
                player.getInventory().setItemInHand(Item.get(Item.AIR));
                player.getInventory().sendContents(player); // 同步客户端
            }
        }

        // 创建邮件数据
        long timestamp = System.currentTimeMillis() / 1000; // 使用秒级时间戳
        EmailData email = new EmailData(
                timestamp,
                keepDays,
                text,
                attachments,
                0, // 初始状态为未读
                player.getName() // 发件人
        );

        player.sendMessage("§a已成功发送邮件给 " + targetPlayer);
        // 存储邮件并保存
        if(targetPlayer.equals("all")) {
            for(String name : config.getKeys()) {
                System.out.println(name);
                if(!name.contains(".")) {
                    sendEmail(name, email);
                }
            }
            return true;
        }
        if(targetPlayer.equals("ol")) {
            Collection<Player> players = MainPlugin.getInstance().getServer().getOnlinePlayers().values();
            for(Player p: players) {
                sendEmail(p.getName(), email);
            }
            return true;
        }
        sendEmail(targetPlayer, email);
        return true;
    }

    private void sendEmail(String targetPlayer, EmailData email) {
        if (MainPlugin.getInstance().getServer().getPlayer(targetPlayer) != null && MainPlugin.getInstance().getServer().getPlayer(targetPlayer).isOnline()) {
        Player player = MainPlugin.getInstance().getServer().getPlayer(targetPlayer);
            emailManager.addEmail(targetPlayer, email);
            player.sendMessage("§a你收到了一封新邮件，输入/xemailopen查看。");
        } else {
            emailManager.addEmailInConfig(targetPlayer, email);
        }
    }
}